package com.zbf.tspring.httpclient;

import okhttp3.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/23  20:41
 * 描述:
 */
@RestController
public class TestOkHttpController {

    /**
     * 作者: LCG
     * 日期: 2021/3/23  21:18
     * 描述: post的方式通过RequestBody传参提交JSON数据
     * @Param []
     * @Return void
     */
    @RequestMapping("okHttp")
    public void testOkHttp() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.callTimeout(100, TimeUnit.SECONDS);
        builder.connectTimeout(100, TimeUnit.SECONDS);
        builder.readTimeout(100,TimeUnit.SECONDS);
        OkHttpClient okHttpClient = builder.build();

        //构建请求
        String json="{\"userName\":\"zhangsan\",\"address\":\"地址\"}";
        RequestBody requestBody = FormBody.create(okhttp3.MediaType.parse("application/json"), json);

        /*FormBody formBody = new FormBody.Builder()
                .addEncoded("key1", "123456")
                .add("userName", "zhangsan")
                .add("address", "地址")
                .build();*/

        Request request = new Request.Builder()
                .addHeader("token", "123456")
                .post(requestBody)
                .url("http://localhost:10001/testUpload")
                .build();

        //发送请求
        Call call = okHttpClient.newCall(request);

        //获取响应
        try {
            Response execute = call.execute();
            ResponseBody body = execute.body();
            byte[] bytes = body.bytes();
            String string = new String(bytes);
            System.out.println("--结果-->"+string);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

   

    /**
     * 作者: LCG
     * 日期: 2021/3/23  21:21
     * 描述: 提交Form表单的形式传参
     * @Param []
     * @Return void   testFormBody
     */
    @RequestMapping("formBody")
    public void test002(MultipartFile[] file) throws IOException {

        //String name, String value, long expiresAt, String domain, String path, boolean secure,
        //boolean httpOnly, boolean hostOnly, boolean persistent
        Cookie cookie = new Cookie
                .Builder()
                .domain("localhost")
                .expiresAt(-1)
                .name("cokkiesName")
                .value("cookiesValue")
                .path("/")
                .build();

        //1、构建HttpClient
        OkHttpClient httpClient = new OkHttpClient.Builder()
                //设置读超时(就是获取响应数据的的超时时间)
                .readTimeout(100, TimeUnit.SECONDS)
                //设置写超时（就是发送数据的时候 如果发送的数据比较大防止超时）
                .writeTimeout(100, TimeUnit.SECONDS)
                .build();


        byte[] bytes1 = file[0].getBytes();

        BASE64Encoder base64Encoder=new BASE64Encoder();
        String encode = base64Encoder.encode(bytes1);


        //2设置请求的表单数据
        FormBody build1 = new FormBody.Builder()
                //设置表单的参数
                .add("userName", "张三三")
                .add("image", encode)
                //设置参数并加密
                .addEncoded("password", "12346698#$$&")
                .build();

        //3、构建请求
        Request request = new Request.Builder()
                .url("http://localhost:10001/testFormBody")
                .addHeader("token", "12345666")
                .post(build1)
                .build();

        //4、发送请求
        try {
            Response execute = httpClient.newCall(request).execute();
            //获取响应结果
            byte[] bytes = execute.body().bytes();
            String parm = new String(bytes);

            System.out.println("==响应的结果==》"+parm);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 作者: LCG
     * 日期: 2021/3/23  23:27
     * 描述: 测试文件的上传包括参数
     * @Param []
     * @Return void
     */
    @RequestMapping("formFile")
    public void test007(MultipartFile file) throws IOException {

        //媒体类型
        MediaType parse = MediaType.parse("multipart/form-data");
        //创建请求体
        RequestBody requestBody = MultipartBody.create(parse, file.getBytes());

        MultipartBody.Builder multiBuilder=new MultipartBody.Builder();
        multiBuilder.addFormDataPart("file",file.getOriginalFilename(),requestBody);
        multiBuilder.addFormDataPart("file","456.jpg",requestBody);
        multiBuilder.addFormDataPart("userName","李四小姐姐");
        multiBuilder.addFormDataPart("password","123456");

        //1、构建OkHttpClient
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        //2、构建请求体
        MultipartBody multipartBody = multiBuilder.build();
        //3、构建请求
        Request request = new Request.Builder()
                .post(multipartBody)
                .addHeader("token", "123456")
                .url("http://localhost:10001/uploadFile")
                .build();

        //4发送请求
        Response execute = okHttpClient.newCall(request).execute();

        //5获取响应的结果
        byte[] bytes = execute.body().bytes();

        String s = new String(bytes);

        System.out.println(s);


    }

}
